package com.chaos.meta.common;


import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.CellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.List;

public class CustomHandler extends AbstractColumnWidthStyleStrategy
{
	private static final int MAX_COLUMN_WIDTH = 255;
	//the maximum column width in Excel is 255 characters

	protected void setColumnWidth(WriteSheetHolder writeSheetHolder, CellData cellData, Cell cell, Head head, int relativeRowIndex, boolean isHead) {

	}

	public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, int relativeRowIndex, boolean isHead) {
		if (isHead && cell.getRowIndex() != 0) {
			int columnWidth = cell.getStringCellValue().getBytes().length;
			if (columnWidth > MAX_COLUMN_WIDTH) {
				columnWidth = MAX_COLUMN_WIDTH;
			} else {
				columnWidth = columnWidth + 3;
			}
			writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
		}

		//设置单元格格式为文本
		Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
		CellStyle cellStyle = workbook.createCellStyle();
		DataFormat dataFormat = workbook.createDataFormat();
		cellStyle.setDataFormat(dataFormat.getFormat("@"));
		cell.setCellStyle(cellStyle);
	}

	@Override
	public void afterCellDispose(CellWriteHandlerContext context) {
		this.setColumnWidth(context);
	}

	@Override
	public void setColumnWidth(CellWriteHandlerContext context) {
		this.setColumnWidth(context.getWriteSheetHolder(), context.getCellDataList(), context.getCell(), context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
	}

	@Override
	public void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
		throw new UnsupportedOperationException("Custom styles must override the setColumnWidth method.");
	}
}